
// @koala-prepend "../../libs/jQuery.md5.js"

$(function(){
	$('.btn-login').click(Page.login);
});

var Page = {};
Page.login = function() {
	var name = $.trim($('.txt-username').val());
	if(name == '') {
		$('.pophint').html('请输入用户名');
		$('.modal-hint').modal('show');
		return;
	}

	var password = $.trim($('.txt-password').val());
	if(password == '') {
		$('.pophint').html('请输入密码');
		$('.modal-hint').modal('show');
		return;
	}

	password = $.md5(password);


	var url = urls.server + '/users';

	$.ajax({
        type: 'POST',
        async: true,
        url: url,
        dataType: 'json',
        data: {
        	name: name,
        	password: password
        },
        success: function(e){
        	if(e.action === "success") {
                var token = Page.getRndStr();
                $.cookie(urls.sname, token, {
                    path: '/',
                    expires: 1
                });
        		location.href = '../home?t=' + token;
        	}
        	else {        		
				$('.pophint').html('用户名或密码错误');
				$('.modal-hint').modal('show');
				$('.txt-password').val('');
        	}
        }
    });
	
}
Page.getRndStr = function(){
    var s = [];
    var a = parseInt(Math.random() * 25) + (Math.random() > 0.5 ? 65 : 97);
    for (var i = 0; i < 10; i++)
    {
        s[i] = Math.random() > 0.5
            ? parseInt(Math.random() * 9)
            : String.fromCharCode(parseInt(Math.random() * 25) + (Math.random() > 0.5 ? 65 : 97));
    }
    return s.join('');
}